/**
 * 
 */
package persistence;

import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author fabiensaulnier
 * 
 */
public class PersistenceSessionFactory {

	private static Logger log = LoggerFactory.getLogger(PersistenceSessionFactory.class);
	protected static ThreadLocal<PersistenceSession> currentSession = new ThreadLocal<PersistenceSession>();

	private PersistenceConfiguration persistenceConfiguration;

	public PersistenceSessionFactory(PersistenceConfiguration configuration) {
		this.persistenceConfiguration = configuration;
	}

	public PersistenceSession openSession() throws PersistenceException {
		log.debug("Ouverture d'une nouvelle session");
		PersistenceSession persistenceSession = new PersistenceSession(persistenceConfiguration);
		return persistenceSession;
	}

	/**
	 * @return the persistenceConfiguration
	 */
	public PersistenceConfiguration getPersistenceConfiguration() {
		return persistenceConfiguration;
	}

	/**
	 * @param persistenceConfiguration
	 *            the persistenceConfiguration to set
	 */
	public void setPersistenceConfiguration(PersistenceConfiguration persistenceConfiguration) {
		this.persistenceConfiguration = persistenceConfiguration;
	}

	public PersistenceSession getCurrentSession() throws PersistenceException {
		log.debug("Getting current Persistence Session ");
		PersistenceSession session = currentSession.get();
		if (session == null) {
			session = openSession();
			currentSession.set(session);
		}
		return session;
	}

	public void close(PersistenceSession session) throws SQLException {
		log.debug("Closing Persistence Session ");
		PersistenceSession current = currentSession.get();
		current.close();
		if (current != null && current == session) {
			currentSession.set(null);
		}
	}

}
